package com.trendata.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.trendata.domain.Shop;
import com.trendata.domain.User;
import com.trendata.service.UserService;
import com.trendata.util.Constants;
import com.trendata.util.JsonResult;

/**
 * 登录权限过滤
 * 
 * @author: HuangXiuXiu Email:243559392@qq.com
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private UserService userService;
	private Logger logger = Logger.getLogger("userLogger");

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String uri = request.getRequestURI();
		if (StringUtils.isEmpty(uri)) {
			return false;
		}
		logger.info("uri:" + uri);

		// user
		if (uri.contains("/user/")) {
			User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
			if (user != null) {
				return true;
			}
		}
		// shop
		else if (uri.contains("/shop/")) {
			Shop shop = (Shop) request.getSession().getAttribute(Constants.SESSION_TYPE_SHOP);
			if (shop != null) {
				return true;
			}
		} else {
			return true;
		}

		// 不登陆，返回403
		PrintWriter printWriter = null;
		try {
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			printWriter = response.getWriter();
			printWriter.write(new JsonResult().setMessage("会话已经过期了哦~请重新登陆了啦!!!!").toJsonString());
		} catch (Exception e) {
			printWriter = response.getWriter();
			printWriter.write(new JsonResult().setMessage("拦截器拦截出现异常:" + e.getMessage()).toJsonString());
		} finally {
			if (printWriter != null) {
				try {
					printWriter.flush();
					printWriter.close();
				} catch (Exception e1) {
				}
			}
		}

		return false;
	}
}
